package com.bestdata.em.drs.receviedatafromDRS.service;


import com.alibaba.fastjson.JSONObject;
import com.bestdata.em.drs.receviedatafromDRS.mapper.DataProcessMapper;
import com.bestdata.em.drs.receviedatafromDRS.model.DataInfo;
import com.bestdata.em.drs.receviedatafromDRS.model.InsertData;
import com.netty.im.client.core.EMDataConnection;
import com.netty.im.client.core.EMDataReceive;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author chizhenyu
 * @title:
 * @description: 接收DMS的数据
 * @date 2019-12-2 13:51:50
 */

@Service
@DependsOn("springContextHolder")
public class DataReceiveProcess extends Thread implements EMDataReceive {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WebApplicationContext webapplicationcontext;

    @Autowired
    private DataProcessMapper dataProcessMapper;

    private Thread thread;
    @Value("${receive.clientKey}")
    private String clientKey = "";
    @Value("${receive.listenip}")
    private String dmsServiceIp = "";
    @Value("${receive.listenport}")
    private int dmsServicePort = 9111;

    @PostConstruct
    public void init() {
        this.thread = new Thread(this);
        this.thread.start();
    }

    @Override
    public void run() {
        EMDataConnection emDataUtil = new  EMDataConnection();

        emDataUtil.start(clientKey,dmsServiceIp , dmsServicePort, this);
        logger.info("Client Key:" + clientKey + "," + dmsServiceIp + "," + dmsServicePort);
    }

    @Override
    public void ConsumptionData(String msg) {
        try {
            if (msg == null){
                logger.error("msg is null");
                return;
            }
            logger.info("msg ==== {}",msg);
            DataInfo deviceData = JSONObject.parseObject(msg, DataInfo.class);

            if(!StringUtils.isEmpty(deviceData.getDevid())){

                InsertData data = new InsertData();

                data.setValue(deviceData.getValue());
                data.setTm(new Date(deviceData.getTm()));
                logger.info("data ==== {}",data);
                dataProcessMapper.insertData(data);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

